<!--
 * @Description:图片根据大小设置
 * @version: v1.0
 * @Author: Wang Xi
 * @Date: 2023-5-18 9:10:00
 * @LastEditors: Wang Xi
 * @LastEditTime: 2023-5-22 10:30:00
-->
<template>
	<view class="image-for-size" @click="$emit('click',$event)" :style="style">
		<image class="image" :src="imgSrc" @error="error" :mode="mode" :style="`background-color:${imgStatus?'':'#ccc'}`"></image>
	</view>
</template>

<script>
	/**
	 * imageForSize 图片
	 * @description 基于image组件，方便尺寸设置，及圆角
	 * @property {String} size 传size则为正方形
	 * @property {String} w 图片宽度 ---传递后覆盖size
	 * @property {String} h 图片高度 ---传递后覆盖size
	 * @property {String} src 图片路径
	 * @property {String} radius 圆角传递百分比或者长度
	 * @property {String} mode uni原生属性
	 */
	export default {
		name: "imageForSize",
		props: {

			size: {
				default: '',
				type: String
			},
			w: {
				default: '',
				type: String
			},
			h: {
				default: '',
				type: String
			},
			src: {
				default: '',
				type: String | null,
				required: true
			},
			radius: {
				default: '',
				type: String
			},
			mode: {
				default: 'aspectFill',
				type: String
			},
			defaultImg: {
				default: '',
			}

		},
		data() {
			return {
				imgSrc: this.src || this.defaultImg, // 图片路径
				imgStatus:!!this.src // 图片状态 没传地址及加载失败均为err --- false
			};
		},
		computed: {
			borderRadius() {
				if (this.radius.includes('%')) {
					return this.radius
				} else {
					return (this.radius || 0) + 'rpx'
				}
			},
			style() {
				const {
					w,
					h,
					size
				} = this
				return {
					width: w || (size + 'rpx'),
					height: h || (size + 'rpx'),
					'border-radius':this.borderRadius,
				}
			},
		},
		methods: {
			error(err) {
				console.log(err);
				this.imgStatus = false
				this.defaultImg && (this.imgSrc = this.defaultImg)
			},
		}
	}
</script>

<style lang="scss" scoped>
	.image-for-size {
		display: flex;
		align-items: center;
		justify-content: center;
		overflow: hidden;
		.image {
			width: 100%;
			height: 100%;
			overflow: hidden;
		}
	}
</style>
